class TopicsController < ApplicationController
  # GET /topics
  # GET /topics.xml
  def index
    @topics = Topic.all
    
  end


  # GET /topics/1
  # GET /topics/1.xml
  def show
    @topic = Topic.find(params[:id])
    @new_comment = Comment.new
    @comments = @topic.comments
    @page = 1
    @user = User.find_by_id(session[:user_id])
   end

  # GET /topics/new
  # GET /topics/new.xml
  def new
    @topic = Topic.new

    render :action=>"new_topic"
  end

  # GET /topics/1/edit
  def edit
    @topic = Topic.find(params[:id])
  end

  # POST /topics
  # POST /topics.xml
  def create
    @topic = Topic.new(params[:topic])
    @topic.visible = 1
    @topic.user_id = session[:user_id]

    if @topic.save
     redirect_to ""
    else
      render :action=>"new_topic"
    end

   end

  # PUT /topics/1
  # PUT /topics/1.xml
  def update
    @topic = Topic.find(params[:id])
    if @topic.update_attributes(params[:topic])
      redirect_to :action=>"show", :id=>@topic.id
    else
      redirect_to :action=>"edit", :id=>@topic.id
    end
   end



  # DELETE /topics/1
  # DELETE /topics/1.xml
  def destroy
    @topic = Topic.find(params[:id])
    activity = Activity.find_by_id( params[:id] )
    if activity
      activity.volunteers.clear
      activity.destroy
    end
    @topic.comments.each do |cm|
      cm.destroy
    end
    @topic.destroy
    redirect_to :controller=>"index"
  end


  def add_new_comment
    @comment = Comment.new(params[:comment])
    @comment.user_id = session[:user_id]
    @comment.topic_id = params[:topic_id]
    @comment.save

    redirect_to  :action => "show" ,:id=> params[:topic_id]
  end


  def next_page
    @comments = @topic.comments
    @comments = Comment.find_on_page(params[:page].to_i, 5)
    @page = params[:page].to_i + 1
    respond_to do |format|
      format.js
    end
  end

  def last_page
    @comments = @topic.comments
    @comments = Comment.find_on_page(params[:page].to_i - 2, 5)
    @page = params[:page].to_i - 1
    respond_to do |format|
      format.js
    end
  end
end
